package com.baidu.iit.pvm.test.complex.behaviors;

import com.baidu.iit.pvm.PvmActivity;
import com.baidu.iit.pvm.PvmTransition;
import com.baidu.iit.pvm.delegate.ActivityBehavior;
import com.baidu.iit.pvm.delegate.ActivityExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 并发流程的执行动作
 * User: huangweili
 * Date: 14-4-15
 * Time: 下午4:29
 */
public class ParallelGateway implements ActivityBehavior {

    private static Logger logger = LoggerFactory.getLogger(ParallelGateway.class);

    public void execute(ActivityExecution execution) {
        PvmActivity activity = execution.getActivity();

        List<PvmTransition> outgoingTransitions = execution.getActivity().getOutgoingTransitions();

        //把当前的activate设置成不可用
        execution.inactivate();

        List<ActivityExecution> joinedExecutions = execution.findInactiveConcurrentExecutions(activity);

        int nbrOfExecutionsToJoin = execution.getActivity().getIncomingTransitions().size();


        int nbrOfExecutionsJoined = joinedExecutions.size();

        if (nbrOfExecutionsJoined==nbrOfExecutionsToJoin) {
            logger.debug("parallel gateway '{}' activates: {} of {} joined", activity.getId(), nbrOfExecutionsJoined, nbrOfExecutionsToJoin);
            execution.takeAll(outgoingTransitions, joinedExecutions);

        } else if (logger.isDebugEnabled()){
            logger.debug("parallel gateway '{}' does not activate: {} of {} joined", activity.getId(), nbrOfExecutionsJoined, nbrOfExecutionsToJoin);
        }
    }
}
